{% extends "base.html" %}
{% block title %}帖子详情 - 城会玩{% endblock %}

{% block style %}
{{ block.super }}
    <style>
        :root {
            --primary: #FF6B35;
            --light: #F8F9FA;
            --dark: #343A40;
        }

        .discussion-detail-container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 2rem 0;
        }

        .discussion-detail-card {
            background: white;
            border-radius: 12px;
            box-shadow: 0 4px 20px rgba(0,0,0,0.08);
            overflow: hidden;
            margin-bottom: 2rem;
        }

        .discussion-header {
            padding: 2rem;
            border-bottom: 1px solid #f0f0f0;
        }

        .user-info {
            display: flex;
            align-items: center;
            margin-bottom: 1rem;
        }

        .user-avatar {
            width: 60px;
            height: 60px;
            border-radius: 50%;
            background: linear-gradient(135deg, var(--primary), #E55A2B);
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-weight: bold;
            font-size: 1.5rem;
            margin-right: 1rem;
        }

        .user-avatar img {
            width: 100%;
            height: 100%;
            border-radius: 50%;
            object-fit: cover;
        }

        .user-details {
            flex: 1;
        }

        .username {
            font-weight: 600;
            font-size: 1.2rem;
            margin-bottom: 0.25rem;
            color: #333;
        }

        .post-time {
            color: #666;
            font-size: 0.9rem;
        }

        .activity-badge {
            display: inline-block;
            background: rgba(255, 107, 53, 0.1);
            color: var(--primary);
            padding: 0.5rem 1rem;
            border-radius: 20px;
            font-weight: 500;
            margin-bottom: 1rem;
        }

        .discussion-content {
            padding: 2rem;
        }

        .discussion-text {
            line-height: 1.8;
            font-size: 1.1rem;
            color: #333;
            margin-bottom: 2rem;
        }

        .discussion-images {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 1rem;
            margin-bottom: 2rem;
        }

        .discussion-image {
            border-radius: 8px;
            overflow: hidden;
            cursor: pointer;
            transition: transform 0.3s;
        }

        .discussion-image:hover {
            transform: scale(1.02);
        }

        .discussion-image img {
            width: 100%;
            height: 200px;
            object-fit: cover;
        }

        .discussion-actions {
            display: flex;
            align-items: center;
            padding: 1.5rem 2rem;
            border-top: 1px solid #f0f0f0;
            background: #fafafa;
            gap: 1rem;
        }

        .action-btn {
            display: flex;
            align-items: center;
            gap: 0.5rem;
            padding: 0.75rem 1.5rem;
            border: none;
            background: white;
            color: #666;
            border-radius: 25px;
            transition: all 0.3s;
            cursor: pointer;
            font-weight: 500;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
        }

        .action-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(0,0,0,0.15);
        }

        .action-btn.liked {
            color: #e74c3c;
            background: rgba(231, 76, 60, 0.1);
        }

        .action-btn.favorited {
            color: #FFD700;
            background: rgba(255, 215, 0, 0.1);
        }

        /* 评论区域样式 */
        .comments-section {
            background: white;
            border-radius: 12px;
            box-shadow: 0 4px 20px rgba(0,0,0,0.08);
            padding: 2rem;
            margin-bottom: 2rem;
        }

        .comments-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 1.5rem;
            padding-bottom: 1rem;
            border-bottom: 1px solid #eee;
        }

        .comments-title {
            font-size: 1.5rem;
            color: #333;
            font-weight: 600;
        }

        .comments-count {
            color: #666;
            font-size: 1rem;
        }

        .comment-form {
            margin-bottom: 2rem;
        }

        .comment-input {
            width: 100%;
            min-height: 100px;
            padding: 1rem;
            border: 1px solid #ddd;
            border-radius: 8px;
            font-family: inherit;
            font-size: 1rem;
            resize: vertical;
            margin-bottom: 1rem;
            transition: border-color 0.3s;
        }

        .comment-input:focus {
            outline: none;
            border-color: var(--primary);
            box-shadow: 0 0 0 2px rgba(255, 107, 53, 0.2);
        }

        .comment-submit {
            background-color: var(--primary);
            color: white;
            border: none;
            padding: 0.8rem 1.5rem;
            border-radius: 5px;
            font-size: 1rem;
            cursor: pointer;
            transition: background-color 0.3s;
        }

        .comment-submit:hover {
            background-color: #E55A2B;
        }

        .comments-list {
            margin-top: 2rem;
        }

        .comment {
            padding: 1.5rem;
            border-bottom: 1px solid #eee;
            position: relative;
            transition: background-color 0.3s;
        }

        .comment:last-child {
            border-bottom: none;
        }

        .comment:hover {
            background-color: #f9fafb;
        }

        /* 评论头像样式 */
        .comment-header {
            display: flex;
            align-items: flex-start;
            gap: 12px;
            margin-bottom: 0.5rem;
        }

        .comment-avatar {
            flex-shrink: 0;
        }

        .avatar-img {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            object-fit: cover;
            border: 2px solid #f0f0f0;
            transition: border-color 0.3s;
        }

        .comment:hover .avatar-img {
            border-color: var(--primary);
        }

        .comment-author-info {
            flex: 1;
            display: flex;
            flex-direction: column;
            gap: 2px;
        }

        .comment-author {
            font-weight: 600;
            color: #333;
            font-size: 0.95rem;
        }

        .comment-date {
            font-size: 0.8rem;
            color: #888;
        }

        .comment-content {
            color: #555;
            line-height: 1.6;
            margin-bottom: 1rem;
            margin-left: 52px;
        }

        .comment-actions {
            display: flex;
            justify-content: flex-start;
            gap: 1rem;
            margin-left: 52px;
        }

        .comment-like-btn, .comment-reply-btn, .comment-delete-btn {
            background: none;
            border: none;
            color: #888;
            font-size: 0.9rem;
            cursor: pointer;
            padding: 0.3rem 0.5rem;
            border-radius: 3px;
            transition: all 0.3s;
            opacity: 0.7;
            display: flex;
            align-items: center;
            gap: 0.3rem;
        }

        .comment:hover .comment-like-btn,
        .comment:hover .comment-reply-btn,
        .comment:hover .comment-delete-btn {
            opacity: 1;
        }

        .comment-like-btn:hover, .comment-reply-btn:hover {
            background-color: rgba(255, 107, 53, 0.1);
            color: var(--primary);
        }

        .comment-like-btn.liked {
            color: #e74c3c;
            background-color: rgba(231, 76, 60, 0.1);
        }

        .comment-delete-btn {
            color: #dc3545;
            background-color: rgba(220, 53, 69, 0.1);
        }

        .comment-delete-btn:hover {
            background-color: rgba(220, 53, 69, 0.2);
        }

        .no-comments {
            text-align: center;
            color: #888;
            padding: 2rem;
        }

        /* 回复相关样式 */
        .replies-list {
            margin-left: 2rem;
            border-left: 2px solid #eee;
            padding-left: 1rem;
            margin-top: 1rem;
        }

        .comment.reply {
            background-color: #f8f9fa;
            border-radius: 8px;
            margin: 0.5rem 0;
            padding: 1rem;
        }

        .reply .avatar-img {
            width: 32px;
            height: 32px;
        }

        .reply .comment-content {
            margin-left: 44px;
        }

        .reply .comment-actions {
            margin-left: 44px;
        }

        .reply-to {
            color: var(--primary);
            font-weight: 600;
            margin-right: 0.5rem;
        }

        .reply-form {
            margin-top: 1rem;
            padding: 1rem;
            background-color: #f9fafb;
            border-radius: 8px;
            margin-left: 52px;
        }

        .reply-input {
            width: 100%;
            min-height: 60px;
            padding: 0.8rem;
            border: 1px solid #ddd;
            border-radius: 5px;
            font-family: inherit;
            font-size: 0.9rem;
            resize: vertical;
            margin-bottom: 0.5rem;
        }

        .reply-input:focus {
            outline: none;
            border-color: var(--primary);
        }

        .reply-actions {
            display: flex;
            gap: 0.5rem;
            justify-content: flex-end;
        }

        .reply-submit, .reply-cancel {
            padding: 0.5rem 1rem;
            border: none;
            border-radius: 5px;
            font-size: 0.9rem;
            cursor: pointer;
            transition: background-color 0.3s;
        }

        .reply-submit {
            background-color: var(--primary);
            color: white;
        }

        .reply-submit:hover {
            background-color: #E55A2B;
        }

        .reply-cancel {
            background-color: #6c757d;
            color: white;
        }

        .reply-cancel:hover {
            background-color: #5a6268;
        }

        /* 动画效果 */
        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(10px); }
            to { opacity: 1; transform: translateY(0); }
        }

        .comment {
            animation: fadeIn 0.3s ease-out;
        }

        /* 通知样式 */
        .notification {
            position: fixed;
            top: 80px;
            right: 20px;
            background: #4caf50;
            color: white;
            padding: 1rem 1.5rem;
            border-radius: 4px;
            box-shadow: 0 4px 12px rgba(0,0,0,0.15);
            z-index: 1050;
            display: flex;
            align-items: center;
            gap: 1rem;
            animation: slideIn 0.3s ease-out;
        }

        .notification.error {
            background: #f44336;
        }

        .notification.info {
            background: #2196f3;
        }

        @keyframes slideIn {
            from { transform: translateX(100%); opacity: 0; }
            to { transform: translateX(0); opacity: 1; }
        }

        .notification-close {
            background: none;
            border: none;
            color: white;
            font-size: 1.2rem;
            cursor: pointer;
            padding: 0;
            width: 20px;
            height: 20px;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .back-link {
            display: inline-flex;
            align-items: center;
            gap: 0.5rem;
            color: var(--primary);
            text-decoration: none;
            font-weight: 500;
            margin-bottom: 1rem;
            transition: all 0.3s;
        }

        .back-link:hover {
            transform: translateX(-5px);
        }

        /* 右侧边栏样式 */
        .sidebar-card {
            background: white;
            border-radius: 12px;
            box-shadow: 0 4px 20px rgba(0,0,0,0.08);
            padding: 1.5rem;
            margin-bottom: 1.5rem;
            border: 1px solid rgba(0,0,0,0.05);
        }

        .sidebar-title {
            font-weight: 600;
            color: var(--primary);
            margin-bottom: 1rem;
            font-size: 1.1rem;
            border-bottom: 2px solid var(--primary);
            padding-bottom: 0.5rem;
        }

        .user-profile-sidebar {
            text-align: center;
            padding: 1rem 0;
        }

        .profile-avatar {
            width: 80px;
            height: 80px;
            border-radius: 50%;
            margin: 0 auto 1rem;
            background: linear-gradient(135deg, var(--primary), #E55A2B);
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-weight: bold;
            font-size: 2rem;
        }

        .profile-avatar img {
            width: 100%;
            height: 100%;
            border-radius: 50%;
            object-fit: cover;
        }

        .profile-name {
            font-weight: 600;
            font-size: 1.2rem;
            margin-bottom: 0.5rem;
            color: #333;
        }

        .profile-bio {
            color: #666;
            font-size: 0.9rem;
            margin-bottom: 1rem;
            line-height: 1.4;
        }

        .profile-stats {
            display: flex;
            justify-content: space-around;
            margin-bottom: 1.5rem;
            padding: 1rem 0;
            border-top: 1px solid #f0f0f0;
            border-bottom: 1px solid #f0f0f0;
        }

        .stat-item {
            text-align: center;
        }

        .stat-number {
            font-weight: 600;
            font-size: 1.1rem;
            color: var(--primary);
            display: block;
        }

        .stat-label {
            font-size: 0.8rem;
            color: #666;
        }

        .action-buttons {
            display: flex;
            gap: 0.5rem;
            margin-bottom: 1rem;
        }

        .btn-follow {
            flex: 1;
            background: var(--primary);
            color: white;
            border: none;
            padding: 0.75rem;
            border-radius: 8px;
            font-weight: 500;
            transition: all 0.3s;
            cursor: pointer;
        }

        .btn-follow:hover {
            background: #E55A2B;
            transform: translateY(-2px);
        }

        .btn-follow.following {
            background: #6c757d;
        }

        .btn-message {
            flex: 1;
            background: white;
            color: var(--primary);
            border: 2px solid var(--primary);
            padding: 0.75rem;
            border-radius: 8px;
            font-weight: 500;
            transition: all 0.3s;
            cursor: pointer;
        }

        .btn-message:hover {
            background: var(--primary);
            color: white;
            transform: translateY(-2px);
        }

        .user-activity {
            margin-top: 1.5rem;
        }

        .activity-item {
            display: flex;
            align-items: center;
            padding: 0.75rem;
            border-radius: 8px;
            transition: background-color 0.3s;
            cursor: pointer;
            margin-bottom: 0.5rem;
        }

        .activity-item:hover {
            background-color: rgba(255, 107, 53, 0.1);
        }

        .activity-avatar {
            width: 40px;
            height: 40px;
            border-radius: 8px;
            margin-right: 0.75rem;
            background-size: cover;
            background-position: center;
        }

        .activity-info {
            flex: 1;
        }

        .activity-title {
            font-weight: 500;
            font-size: 0.9rem;
            margin-bottom: 0.25rem;
            color: #333;
        }

        .activity-meta {
            font-size: 0.8rem;
            color: #666;
        }

        .empty-activity {
            text-align: center;
            padding: 1rem;
            color: #666;
            font-size: 0.9rem;
        }

        /* 私信模态框样式 */
        .message-modal .modal-content {
            border-radius: 16px;
            border: none;
            box-shadow: 0 10px 40px rgba(0,0,0,0.1);
        }

        .message-modal .modal-header {
            background: linear-gradient(135deg, var(--primary), var(--secondary));
            color: white;
            border-bottom: none;
            border-radius: 16px 16px 0 0;
            padding: 1.25rem 1.5rem;
        }

        .message-modal .modal-body {
            padding: 1.5rem;
        }

        .message-list {
            max-height: 280px;
            overflow-y: auto;
            margin-bottom: 1rem;
            padding: 0.5rem;
        }

        .message-item {
            padding: 0.875rem 1rem;
            margin-bottom: 0.75rem;
            border-radius: 12px;
            border: 1px solid #e9ecef;
            line-height: 1.5;
        }

        .message-sender {
            background: linear-gradient(135deg, #e3f2fd, #f3e5f5);
            margin-left: 1.5rem;
        }

        .message-receiver {
            background: #f8f9fa;
            margin-right: 1.5rem;
        }

        .message-time {
            font-size: 0.75rem;
            color: #6c757d;
            margin-top: 0.375rem;
        }

        /* 响应式设计 */
        @media (max-width: 768px) {
            .discussion-detail-container {
                padding: 1rem;
            }

            .discussion-header,
            .discussion-content {
                padding: 1.5rem;
            }

            .discussion-actions {
                flex-wrap: wrap;
                justify-content: center;
            }

            .action-btn {
                flex: 1;
                min-width: 120px;
                justify-content: center;
            }

            .discussion-images {
                grid-template-columns: 1fr;
            }

            .action-buttons {
                flex-direction: column;
            }

            .comment-content {
                margin-left: 0;
            }

            .comment-actions {
                margin-left: 0;
            }

            .replies-list {
                margin-left: 1rem;
            }

            .reply-form {
                margin-left: 1rem;
            }
        }
    </style>
{% endblock %}

{% block content %}
    {% include "nav.html" %}

    <main>
        <!-- 消息提示容器 -->
        <div class="alert-container">
            {% if messages %}
                {% for message in messages %}
                    <div class="alert alert-{{ message.tags }} alert-dismissible fade show" role="alert">
                        <i class="fas
                            {% if message.tags == 'success' %}fa-check-circle
                            {% elif message.tags == 'error' %}fa-exclamation-circle
                            {% else %}fa-info-circle{% endif %} me-2"></i>
                        {{ message }}
                        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                    </div>
                {% endfor %}
            {% endif %}
        </div>

        <div class="container">
            <div class="discussion-detail-container">
                <!-- 返回链接 -->
                <a href="{% url 'social' %}" class="back-link">
                    <i class="fas fa-arrow-left"></i>
                    返回社区
                </a>

                <div class="row">
                    <!-- 左侧内容区域 -->
                    <div class="col-lg-8">
                        <!-- 帖子详情卡片 -->
                        <div class="discussion-detail-card">
                            <!-- 帖子头部 -->
                            <div class="discussion-header">
                                <div class="user-info">
                                    <div class="user-avatar">
                                        {% if discussion.user.avatar %}
                                            <img src="{{ discussion.user.avatar.url }}" alt="{{ discussion.user.username }}">
                                        {% else %}
                                            {{ discussion.user.username|first|upper }}
                                        {% endif %}
                                    </div>
                                    <div class="user-details">
                                        <div class="username">{{ discussion.user.username }}</div>
                                        <div class="post-time">
                                            <i class="far fa-clock me-1"></i>
                                            {{ discussion.created_at|date:"Y年m月d日 H:i" }}
                                        </div>
                                    </div>
                                </div>

                                <div class="activity-badge">
                                    <i class="fas fa-calendar-alt me-2"></i>
                                    {{ discussion.activity.title }}
                                </div>
                            </div>

                            <!-- 帖子内容 -->
                            <div class="discussion-content">
                                <div class="discussion-text">
                                    {{ discussion.content|linebreaks }}
                                </div>

                                {% if discussion.images %}
                                <div class="discussion-images">
                                    {% for image in discussion.images %}
                                    <div class="discussion-image">
                                        <img src="{{ image.url }}" alt="帖子图片" loading="lazy">
                                    </div>
                                    {% endfor %}
                                </div>
                                {% endif %}
                            </div>

                            <!-- 操作按钮 -->
                            <div class="discussion-actions">
                                <button class="action-btn like-btn" data-discussion-id="{{ discussion.id }}">
                                    <i class="far fa-heart"></i>
                                    <span>点赞</span>
                                    <span class="count">{{ discussion.like_count }}</span>
                                </button>

                                <button class="action-btn comment-scroll-btn">
                                    <i class="far fa-comment"></i>
                                    <span>评论</span>
                                    <span class="count">{{ discussion.comment_count }}</span>
                                </button>

                                <button class="action-btn favorite-btn" data-discussion-id="{{ discussion.id }}">
                                    <i class="far fa-star"></i>
                                    <span>收藏</span>
                                    <span class="count">{{ discussion.favorites.count }}</span>
                                </button>

                                <button class="action-btn share-btn" data-discussion-id="{{ discussion.id }}">
                                    <i class="fas fa-share"></i>
                                    <span>分享</span>
                                    <span class="count">{{ discussion.shares_count }}</span>
                                </button>

                                {% if user.is_authenticated and discussion.user == user %}
                                <button class="action-btn delete-btn" data-discussion-id="{{ discussion.id }}" style="background: rgba(220, 53, 69, 0.1); color: #dc3545;">
                                    <i class="fas fa-trash"></i>
                                    <span>删除</span>
                                </button>
                                {% endif %}
                            </div>
                        </div>

                        <!-- 评论区域 -->
                        <div class="comments-section" id="comments-section">
                            <div class="comments-header">
                                <h2 class="comments-title">评论</h2>
                                <span class="comments-count" id="commentsCount">{{ comments|length }} 条评论</span>
                            </div>

                            {% if user.is_authenticated %}
                            <!-- 评论表单 -->
                            <div class="comment-form">
                                <textarea class="comment-input" id="commentInput" placeholder="写下你的评论..."></textarea>
                                <button class="comment-submit" id="commentSubmit">发布评论</button>
                            </div>
                            {% else %}
                            <div class="comment-form">
                                <p style="color: #888; text-align: center; padding: 1rem;">
                                    请<a href="{% url 'login' %}" style="color: var(--primary);">登录</a>后发表评论
                                </p>
                            </div>
                            {% endif %}

                            <!-- 评论列表 -->
                            <div class="comments-list" id="commentsList">
                                {% for comment in comments %}
                                <div class="comment" data-comment-id="{{ comment.id }}">
                                    <div class="comment-header">
                                        <div class="comment-avatar">
                                            {% if comment.user.avatar %}
                                                <img src="{{ comment.user.avatar.url }}" alt="{{ comment.user.username }}" class="avatar-img" onerror="handleAvatarError(this)">
                                            {% else %}
                                                <div class="avatar-img" style="background: linear-gradient(135deg, var(--primary), #E55A2B); color: white; display: flex; align-items: center; justify-content: center; font-weight: bold;">
                                                    {{ comment.user.username|first|upper }}
                                                </div>
                                            {% endif %}
                                        </div>
                                        <div class="comment-author-info">
                                            <span class="comment-author">{{ comment.user.username }}</span>
                                            <span class="comment-date">{{ comment.created_at|date:"Y-m-d H:i" }}</span>
                                        </div>
                                    </div>
                                    <div class="comment-content">{{ comment.content|linebreaks }}</div>
                                    <div class="comment-actions">
                                        {% if user.is_authenticated %}
                                        <button class="comment-like-btn {% if comment.user_liked %}liked{% endif %}" data-comment-id="{{ comment.id }}">
                                            <i class="far fa-heart"></i>
                                            <span class="comment-like-count">{{ comment.likes_count }}</span>
                                        </button>
                                        <button class="comment-reply-btn" data-comment-id="{{ comment.id }}">
                                            <i class="fas fa-reply"></i> 回复
                                        </button>
                                        {% endif %}
                                        {% if user.is_authenticated and comment.user == user %}
                                        <button class="comment-delete-btn" data-comment-id="{{ comment.id }}">
                                            <i class="fas fa-trash"></i> 删除
                                        </button>
                                        {% endif %}
                                    </div>

                                    <!-- 回复表单 -->
                                    {% if user.is_authenticated %}
                                    <div class="reply-form" id="replyForm-{{ comment.id }}" style="display: none;">
                                        <textarea class="reply-input" placeholder="写下你的回复..."></textarea>
                                        <div class="reply-actions">
                                            <button class="reply-submit" data-comment-id="{{ comment.id }}">回复</button>
                                            <button class="reply-cancel">取消</button>
                                        </div>
                                    </div>
                                    {% endif %}

                                    <!-- 回复列表 -->
                                    <div class="replies-list">
                                        {% for reply in comment.replies.all %}
                                        <div class="comment reply" data-comment-id="{{ reply.id }}">
                                            <div class="comment-header">
                                                <div class="comment-avatar">
                                                    {% if reply.user.avatar %}
                                                        <img src="{{ reply.user.avatar.url }}" alt="{{ reply.user.username }}" class="avatar-img" onerror="handleAvatarError(this)">
                                                    {% else %}
                                                        <div class="avatar-img" style="background: linear-gradient(135deg, var(--primary), #E55A2B); color: white; display: flex; align-items: center; justify-content: center; font-weight: bold; font-size: 0.8rem;">
                                                            {{ reply.user.username|first|upper }}
                                                        </div>
                                                    {% endif %}
                                                </div>
                                                <div class="comment-author-info">
                                                    <span class="comment-author">{{ reply.user.username }}</span>
                                                    <span class="comment-date">{{ reply.created_at|date:"Y-m-d H:i" }}</span>
                                                </div>
                                            </div>
                                            <div class="comment-content">
                                                <span class="reply-to">@{{ comment.user.username }}</span>
                                                {{ reply.content|linebreaks }}
                                            </div>
                                            <div class="comment-actions">
                                                {% if user.is_authenticated %}
                                                <button class="comment-like-btn {% if reply.user_liked %}liked{% endif %}" data-comment-id="{{ reply.id }}">
                                                    <i class="far fa-heart"></i>
                                                    <span class="comment-like-count">{{ reply.likes_count }}</span>
                                                </button>
                                                <button class="comment-reply-btn" data-comment-id="{{ comment.id }}">
                                                    <i class="fas fa-reply"></i> 回复
                                                </button>
                                                {% endif %}
                                                {% if user.is_authenticated and reply.user == user %}
                                                <button class="comment-delete-btn" data-comment-id="{{ reply.id }}">
                                                    <i class="fas fa-trash"></i> 删除
                                                </button>
                                                {% endif %}
                                            </div>
                                        </div>
                                        {% endfor %}
                                    </div>
                                </div>
                                {% empty %}
                                <div class="no-comments" id="noComments">
                                    <i class="far fa-comment-dots" style="font-size: 2rem; margin-bottom: 1rem; color: #ddd;"></i>
                                    <p>还没有评论，快来发表第一条评论吧！</p>
                                </div>
                                {% endfor %}
                            </div>
                        </div>
                    </div>

                    <!-- 右侧边栏 -->
                    <div class="col-lg-4">
                        <!-- 作者信息卡片 -->
                        <div class="sidebar-card">
                            <div class="user-profile-sidebar">
                                <div class="profile-avatar">
                                    {% if discussion.user.avatar %}
                                        <img src="{{ discussion.user.avatar.url }}" alt="{{ discussion.user.username }}">
                                    {% else %}
                                        {{ discussion.user.username|first|upper }}
                                    {% endif %}
                                </div>
                                <div class="profile-name">{{ discussion.user.username }}</div>
                                <div class="profile-bio">
                                    {% if discussion.user.bio %}
                                        {{ discussion.user.bio }}
                                    {% else %}
                                        这个用户还没有填写个人简介
                                    {% endif %}
                                </div>

                                <div class="profile-stats">
                                    <div class="stat-item">
                                        <span class="stat-number">{{ discussion.user.discussion_posts.count }}</span>
                                        <span class="stat-label">帖子</span>
                                    </div>
                                    <div class="stat-item">
                                        <span class="stat-number">{% if discussion.user.followers %}{{ discussion.user.followers.count }}{% else %}0{% endif %}</span>
                                        <span class="stat-label">粉丝</span>
                                    </div>
                                    {% if user.is_authenticated and user != discussion.user %}
                                    <div class="action-buttons">
                                        <button class="btn btn-outline-primary btn-sm follow-btn"
                                                data-user-id="{{ discussion.user.id }}"
                                                onclick="toggleFollow(this)">
                                            <i class="fas {% if is_following %}fa-check{% else %}fa-plus{% endif %} me-1"></i>
                                            <span class="follow-text">{% if is_following %}已关注{% else %}关注{% endif %}</span>
                                        </button>
                                        <button class="btn btn-message btn-sm" data-bs-toggle="modal" data-bs-target="#messageModal">
                                            <i class="fas fa-envelope me-1"></i>
                                            私信
                                        </button>
                                    </div>
                                    {% elif user.is_authenticated and user == discussion.user %}
                                    <div class="action-buttons">
                                        <a href="{% url 'person_center' %}" class="btn btn-primary btn-sm" style="text-decoration: none; display: block;">
                                            <i class="fas fa-user-edit me-1"></i>
                                            编辑资料
                                        </a>
                                    </div>
                                    {% else %}
                                    <div class="alert alert-warning">
                                        <small>登录后关注用户或发送私信</small>
                                    </div>
                                {% endif %}
                                </div>
                            </div>
                        </div>

                        <!-- 作者的其他帖子 -->
                        <div class="sidebar-card">
                            <h5 class="sidebar-title">
                                <i class="fas fa-file-alt me-2"></i>
                                作者的其他帖子
                            </h5>
                            <div class="user-activity">
                                {% for post in discussion.user.discussion_posts.all|slice:":5" %}
                                    {% if post.id != discussion.id %}
                                    <div class="activity-item" onclick="window.location.href='{% url 'discussion_detail' post.id %}'">
                                        <div class="activity-avatar" style="background-color: #f8f9fa; display: flex; align-items: center; justify-content: center;">
                                            <i class="fas fa-file-text text-muted"></i>
                                        </div>
                                        <div class="activity-info">
                                            <div class="activity-title">{{ post.activity.title }}</div>
                                            <div class="activity-meta">
                                                {{ post.created_at|date:"m月d日" }} · {{ post.like_count }} 赞
                                            </div>
                                        </div>
                                    </div>
                                    {% endif %}
                                {% empty %}
                                    <div class="empty-activity">
                                        <i class="far fa-file-alt"></i>
                                        <p>暂无其他帖子</p>
                                    </div>
                                {% endfor %}
                            </div>
                        </div>

                        <!-- 相关活动 -->
                        <div class="sidebar-card">
                            <h5 class="sidebar-title">
                                <i class="fas fa-calendar me-2"></i>
                                相关活动
                            </h5>
                            <div class="user-activity">
                                <div class="activity-item" onclick="window.location.href='{% url 'active_detail' discussion.activity.id %}'">
                                    <div class="activity-avatar" style="background-image: url('{{ discussion.activity.image.url }}')"></div>
                                    <div class="activity-info">
                                        <div class="activity-title">{{ discussion.activity.title }}</div>
                                        <div class="activity-meta">
                                            {{ discussion.activity.start_time|date:"m月d日" }} · {{ discussion.activity.current_participants }}/{{ discussion.activity.max_participants }}人
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

    <!-- 私信模态框 -->
<div class="modal fade message-modal" id="messageModal" tabindex="-1" aria-labelledby="messageModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="messageModalLabel">
                    <i class="fas fa-envelope me-2"></i>发送私信给 {{ discussion.user.username }}
                </h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <div class="message-list" id="messageList">
                    <div class="text-center text-muted py-4">
                        <i class="fas fa-comments fa-2x mb-2"></i>
                        <p class="mb-0">开始与{{ discussion.user.username }}的对话</p>
                    </div>
                </div>
                <form id="messageForm">
                    {% csrf_token %}
                    <input type="hidden" name="receiver_id" value="{{ discussion.user.id }}">
                    <div class="mb-3">
                        <textarea class="form-control" id="messageContent" name="content"
                                  rows="3" placeholder="输入您想说的话..." required></textarea>
                    </div>
                    <div class="d-flex justify-content-between align-items-center">
                        <small class="text-muted">私信仅双方可见</small>
                        <button type="submit" class="btn btn-primary">
                            <i class="fas fa-paper-plane me-1"></i>发送
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>
    </main>
<script>
document.addEventListener('DOMContentLoaded', function() {
    const csrfToken = '{{ csrf_token }}';
    const discussionId = {{ discussion.id }};
    let isSubmitting = false;

    // 调试信息
    console.log('页面加载完成，讨论ID:', discussionId);
    console.log('CSRF Token:', csrfToken ? '已设置' : '未设置');

    // 滚动到评论区域
    const commentScrollBtn = document.querySelector('.comment-scroll-btn');
    if (commentScrollBtn) {
        commentScrollBtn.addEventListener('click', function() {
            document.getElementById('comments-section').scrollIntoView({
                behavior: 'smooth'
            });
        });
    }

    // 初始化功能
    initFunctions();

    function initFunctions() {
        initPostFunctions();
        initCommentFunctions();
        initReplyFunctions();
        initAvatarFunctions(); // 初始化头像功能
    }

    // 帖子相关功能
    function initPostFunctions() {
        // 帖子点赞功能
        const likeBtn = document.querySelector('.like-btn');
        if (likeBtn) {
            likeBtn.addEventListener('click', function() {
                if (!{{ user.is_authenticated|yesno:"true,false" }}) {
                    showNotification('请先登录', 'error');
                    return;
                }
                handlePostLike(this);
            });
        }

        // 收藏功能
        const favoriteBtn = document.querySelector('.favorite-btn');
        if (favoriteBtn) {
            favoriteBtn.addEventListener('click', function() {
                if (!{{ user.is_authenticated|yesno:"true,false" }}) {
                    showNotification('请先登录', 'error');
                    return;
                }
                handleFavorite(this);
            });
        }

        // 分享功能
        const shareBtn = document.querySelector('.share-btn');
        if (shareBtn) {
            shareBtn.addEventListener('click', function() {
                if (!{{ user.is_authenticated|yesno:"true,false" }}) {
                    showNotification('请先登录', 'error');
                    return;
                }
                handleShare(this);
            });
        }

        // 删除帖子功能
        const deleteBtn = document.querySelector('.delete-btn');
        if (deleteBtn) {
            deleteBtn.addEventListener('click', function() {
                handleDeletePost();
            });
        }
    }

    // 评论相关功能
    function initCommentFunctions() {
        // 评论提交
        const commentSubmit = document.getElementById('commentSubmit');
        if (commentSubmit) {
            commentSubmit.addEventListener('click', handleCommentSubmit);
        }

        // 评论列表事件委托
        const commentsList = document.getElementById('commentsList');
        if (commentsList) {
            commentsList.addEventListener('click', handleCommentAction);
        }

        // 回车键提交评论
        const commentInput = document.getElementById('commentInput');
        if (commentInput) {
            commentInput.addEventListener('keydown', function(e) {
                if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') {
                    e.preventDefault();
                    handleCommentSubmit();
                }
            });
        }
    }

    // 回复相关功能
    function initReplyFunctions() {
        // 回复按钮点击事件
        document.addEventListener('click', function(e) {
            if (e.target.closest('.comment-reply-btn')) {
                const btn = e.target.closest('.comment-reply-btn');
                const commentId = btn.dataset.commentId;
                const replyForm = document.getElementById(`replyForm-${commentId}`);
                if (replyForm) {
                    // 隐藏其他回复表单
                    document.querySelectorAll('.reply-form').forEach(form => {
                        if (form.id !== `replyForm-${commentId}`) {
                            form.style.display = 'none';
                        }
                    });

                    replyForm.style.display = replyForm.style.display === 'none' ? 'block' : 'none';
                    if (replyForm.style.display === 'block') {
                        const textarea = replyForm.querySelector('.reply-input');
                        textarea.focus();
                    }
                }
            }

            // 取消回复
            if (e.target.closest('.reply-cancel')) {
                const btn = e.target.closest('.reply-cancel');
                const replyForm = btn.closest('.reply-form');
                if (replyForm) {
                    replyForm.style.display = 'none';
                    const textarea = replyForm.querySelector('.reply-input');
                    textarea.value = '';
                }
            }

            // 提交回复
            if (e.target.closest('.reply-submit')) {
                const btn = e.target.closest('.reply-submit');
                const commentId = btn.dataset.commentId;
                handleReplySubmit(commentId);
            }
        });
    }

    // 头像相关功能
    function initAvatarFunctions() {
        // 初始化所有头像
        refreshAllAvatars();

        // 添加手动刷新头像按钮
        addAvatarRefreshButton();
    }

    // 异步加载头像函数 - 使用当前用户信息
async function loadUserAvatar(userId, username, avatarUrl, element) {
    return new Promise((resolve) => {
        // 如果有头像URL，直接使用
        if (avatarUrl && avatarUrl !== 'null' && avatarUrl !== '' && avatarUrl !== 'undefined') {
            const img = new Image();
            img.onload = function() {
                // 头像加载成功
                element.innerHTML = `<img src="${avatarUrl}" alt="${username}" class="avatar-img" onerror="handleAvatarError(this)">`;
                resolve(true);
            };
            img.onerror = function() {
                // 头像加载失败，使用默认头像
                console.log('头像加载失败:', avatarUrl);
                createDefaultAvatar(username, element);
                resolve(false);
            };
            img.src = avatarUrl;

            // 设置超时，防止长时间加载
            setTimeout(() => {
                if (!img.complete) {
                    console.log('头像加载超时:', avatarUrl);
                    createDefaultAvatar(username, element);
                    resolve(false);
                }
            }, 5000);
        } else {
            // 没有头像URL，使用默认头像
            console.log('无头像URL，使用默认头像:', username);
            createDefaultAvatar(username, element);
            resolve(false);
        }
    });
}

    // 添加头像刷新功能
    function refreshAllAvatars() {
        console.log('刷新所有头像...');

        // 刷新帖子作者头像
        const postAvatar = document.querySelector('.user-avatar');
        if (postAvatar) {
            const username = document.querySelector('.username')?.textContent || '用户';
            const img = postAvatar.querySelector('img');
            if (img && img.src) {
                // 重新加载图片
                const newSrc = img.src + (img.src.includes('?') ? '&' : '?') + 't=' + Date.now();
                img.src = newSrc;
            }
        }

        // 刷新评论和回复头像
        const avatarContainers = document.querySelectorAll('.comment-avatar');
        avatarContainers.forEach(container => {
            const img = container.querySelector('img');
            const defaultAvatar = container.querySelector('.avatar-img[style]');
            const username = container.closest('.comment')?.querySelector('.comment-author')?.textContent || '用户';

            if (img && img.src) {
                // 重新加载图片，添加时间戳避免缓存
                const newSrc = img.src + (img.src.includes('?') ? '&' : '?') + 't=' + Date.now();
                const newImg = new Image();
                newImg.onload = function() {
                    img.src = newSrc;
                };
                newImg.onerror = function() {
                    // 如果重新加载失败，保持原状
                    console.log('头像重新加载失败:', username);
                };
                newImg.src = newSrc;
            } else if (defaultAvatar) {
                // 对于默认头像，可以尝试重新获取用户信息
                const commentElement = container.closest('.comment');
                const commentId = commentElement?.dataset.commentId;
                if (commentId) {
                    // 可以在这里添加重新获取用户头像信息的逻辑
                    console.log('尝试重新获取用户头像:', username, commentId);
                }
            }
        });
    }

    // 添加定期刷新头像的功能（可选）
    function startAvatarAutoRefresh(interval = 30000) {
        setInterval(() => {
            refreshAllAvatars();
        }, interval);
    }

    // 添加手动刷新头像按钮
    function addAvatarRefreshButton() {
        // 检查是否已存在刷新按钮
        if (document.getElementById('avatar-refresh-btn')) {
            return;
        }

        const refreshBtn = document.createElement('button');
        refreshBtn.id = 'avatar-refresh-btn';
        refreshBtn.innerHTML = '<i class="fas fa-sync-alt"></i> 刷新头像';
        refreshBtn.style.cssText = `
            position: fixed;
            bottom: 20px;
            right: 20px;
            background: var(--primary);
            color: white;
            border: none;
            padding: 0.5rem 1rem;
            border-radius: 20px;
            cursor: pointer;
            z-index: 1000;
            box-shadow: 0 2px 10px rgba(0,0,0,0.2);
            font-size: 0.8rem;
            transition: all 0.3s ease;
        `;

        refreshBtn.addEventListener('mouseenter', function() {
            this.style.transform = 'scale(1.05)';
            this.style.boxShadow = '0 4px 15px rgba(0,0,0,0.3)';
        });

        refreshBtn.addEventListener('mouseleave', function() {
            this.style.transform = 'scale(1)';
            this.style.boxShadow = '0 2px 10px rgba(0,0,0,0.2)';
        });

        refreshBtn.addEventListener('click', function() {
            // 添加点击动画
            this.style.transform = 'scale(0.95)';
            setTimeout(() => {
                this.style.transform = 'scale(1)';
            }, 150);

            refreshAllAvatars();
            showNotification('头像刷新中...', 'info');
        });

        document.body.appendChild(refreshBtn);
    }

    // 帖子点赞处理
    function handlePostLike(button) {
        const discussionId = button.dataset.discussionId;
        const url = `/meet/social/discussion/${discussionId}/like/`;

        console.log('点赞请求:', url);

        fetch(url, {
            method: 'POST',
            headers: {
                'X-CSRFToken': csrfToken,
                'X-Requested-With': 'XMLHttpRequest'
            },
        })
        .then(response => {
            console.log('点赞响应状态:', response.status);
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }
            return response.json();
        })
        .then(data => {
            console.log('点赞响应数据:', data);
            if (data.success) {
                const heartIcon = button.querySelector('i');
                const countSpan = button.querySelector('.count');

                if (data.liked) {
                    heartIcon.className = 'fas fa-heart';
                    button.classList.add('liked');
                } else {
                    heartIcon.className = 'far fa-heart';
                    button.classList.remove('liked');
                }

                countSpan.textContent = data.like_count;
                showNotification(data.liked ? '点赞成功！' : '已取消点赞');
            } else {
                showNotification(data.message || '操作失败', 'error');
            }
        })
        .catch(error => {
            console.error('点赞错误:', error);
            showNotification('网络错误，请重试', 'error');
        });
    }

    // 收藏处理
    function handleFavorite(button) {
        const discussionId = button.dataset.discussionId;
        const url = `/meet/social/discussion/${discussionId}/favorite/`;

        fetch(url, {
            method: 'POST',
            headers: {
                'X-CSRFToken': csrfToken,
                'X-Requested-With': 'XMLHttpRequest'
            },
        })
        .then(response => {
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }
            return response.json();
        })
        .then(data => {
            console.log('收藏响应数据:', data);
            if (data.success) {
                const starIcon = button.querySelector('i');
                const countSpan = button.querySelector('.count');

                if (data.favorited) {
                    starIcon.className = 'fas fa-star';
                    button.classList.add('favorited');
                } else {
                    starIcon.className = 'far fa-star';
                    button.classList.remove('favorited');
                }

                countSpan.textContent = data.favorite_count;
                showNotification(data.favorited ? '收藏成功！' : '已取消收藏');
            } else {
                showNotification(data.message || '操作失败', 'error');
            }
        })
        .catch(error => {
            console.error('收藏错误:', error);
            showNotification('网络错误，请重试', 'error');
        });
    }

    // 分享处理
    function handleShare(button) {
        const discussionId = button.dataset.discussionId;
        const url = `/meet/social/discussion/${discussionId}/share/`;

        fetch(url, {
            method: 'POST',
            headers: {
                'X-CSRFToken': csrfToken,
                'X-Requested-With': 'XMLHttpRequest'
            },
        })
        .then(response => {
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }
            return response.json();
        })
        .then(data => {
            console.log('分享响应数据:', data);
            if (data.success) {
                const countSpan = button.querySelector('.count');
                countSpan.textContent = data.shares_count;

                // 复制链接到剪贴板
                const shareUrl = window.location.href;
                navigator.clipboard.writeText(shareUrl).then(() => {
                    showNotification('链接已复制到剪贴板！');
                }).catch(() => {
                    showNotification('复制失败，请手动复制链接', 'error');
                });
            } else {
                showNotification(data.message || '分享失败', 'error');
            }
        })
        .catch(error => {
            console.error('分享错误:', error);
            showNotification('网络错误，请重试', 'error');
        });
    }

    // 删除帖子
    function handleDeletePost() {
        if (!confirm('确定要删除这个帖子吗？此操作不可恢复。')) {
            return;
        }

        const discussionId = {{ discussion.id }};
        const url = `/meet/social/discussion/${discussionId}/delete/`;

        fetch(url, {
            method: 'POST',
            headers: {
                'X-CSRFToken': csrfToken,
                'X-Requested-With': 'XMLHttpRequest'
            },
        })
        .then(response => {
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }
            return response.json();
        })
        .then(data => {
            console.log('删除响应数据:', data);
            if (data.success) {
                showNotification('帖子删除成功');
                setTimeout(() => {
                    window.location.href = '/meet/social/';
                }, 1500);
            } else {
                showNotification(data.message || '删除失败', 'error');
            }
        })
        .catch(error => {
            console.error('删除错误:', error);
            showNotification('网络错误，请重试', 'error');
        });
    }

    // 评论提交处理
    function handleCommentSubmit() {
    if (isSubmitting) return;

    const commentInput = document.getElementById('commentInput');
    const content = commentInput.value.trim();

    if (!content) {
        showNotification('评论内容不能为空', 'error');
        commentInput.focus();
        return;
    }

    if (content.length > 1000) {
        showNotification('评论内容不能超过1000字', 'error');
        return;
    }

    isSubmitting = true;
    const submitBtn = document.getElementById('commentSubmit');
    const originalText = submitBtn.textContent;
    submitBtn.disabled = true;
    submitBtn.textContent = '发布中...';

    const url = `/meet/social/discussion/${discussionId}/comment/`;

    console.log('评论提交:', { url, content });

    const formData = new FormData();
    formData.append('content', content);
    formData.append('csrfmiddlewaretoken', csrfToken);

    fetch(url, {
        method: 'POST',
        headers: {
            'X-Requested-With': 'XMLHttpRequest'
        },
        body: formData
    })
    .then(response => {
        console.log('评论响应状态:', response.status);
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        return response.json();
    })
    .then(data => {
        console.log('评论响应数据:', data);
        if (data.success) {
            commentInput.value = '';

            // 根据后端返回的数据结构调整 - 修复版本
            let commentData;
            if (data.comment) {
                // 如果后端返回完整的 comment 对象
                commentData = data.comment;
            } else if (data.comment_id) {
                // 如果后端返回 comment_id 和其他字段
                commentData = {
                    id: data.comment_id,
                    content: data.content || content,
                    username: data.username || '当前用户',
                    user_avatar: data.user_avatar || '',
                    created_at: data.created_at || new Date().toLocaleString(),
                    likes_count: data.likes_count || 0,
                    user_id: data.user_id || null
                };
            } else {
                // 如果都没有，使用默认数据
                commentData = {
                    id: Date.now(), // 临时ID
                    content: content,
                    username: '当前用户',
                    user_avatar: '',
                    created_at: new Date().toLocaleString(),
                    likes_count: 0,
                    user_id: null
                };
            }

            console.log('处理后的评论数据:', commentData);
            addNewComment(commentData);
            updateCommentCount(1);
            showNotification('评论发布成功！');
        } else {
            if (data.redirect) {
                window.location.href = data.redirect;
            } else {
                showNotification(data.message || '评论失败', 'error');
            }
        }
    })
    .catch(error => {
        console.error('评论错误:', error);
        showNotification('网络错误，请重试', 'error');
    })
    .finally(() => {
        isSubmitting = false;
        submitBtn.disabled = false;
        submitBtn.textContent = originalText;
    });
}

    // 回复提交处理
    function handleReplySubmit(parentCommentId) {
    const replyForm = document.getElementById(`replyForm-${parentCommentId}`);
    const textarea = replyForm.querySelector('.reply-input');
    const content = textarea.value.trim();

    if (!content) {
        showNotification('回复内容不能为空', 'error');
        textarea.focus();
        return;
    }

    if (content.length > 1000) {
        showNotification('回复内容不能超过1000字', 'error');
        return;
    }

    const submitBtn = replyForm.querySelector('.reply-submit');
    const originalText = submitBtn.textContent;
    submitBtn.disabled = true;
    submitBtn.textContent = '回复中...';

    const url = `/meet/social/discussion/${discussionId}/comment/`;

    console.log('回复提交:', {
        url,
        content,
        parentCommentId,
        discussionId
    });

    const formData = new FormData();
    formData.append('content', content);
    formData.append('parent_comment_id', parentCommentId);
    formData.append('csrfmiddlewaretoken', csrfToken);

    fetch(url, {
        method: 'POST',
        headers: {
            'X-Requested-With': 'XMLHttpRequest'
        },
        body: formData
    })
    .then(response => {
        console.log('回复响应状态:', response.status);
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        return response.json();
    })
    .then(data => {
        console.log('回复响应数据:', data);
        if (data.success) {
            textarea.value = '';
            replyForm.style.display = 'none';

            // 根据后端返回的数据结构构造回复数据 - 修复版本
            let replyData;
            if (data.comment) {
                replyData = data.comment;
            } else if (data.comment_id) {
                replyData = {
                    id: data.comment_id,
                    content: data.content || content,
                    username: data.username || '当前用户',
                    user_avatar: data.user_avatar || '',
                    parent_username: data.parent_username || '',
                    created_at: data.created_at || new Date().toLocaleString(),
                    likes_count: data.likes_count || 0,
                    parent_comment_id: parentCommentId,
                    user_id: data.user_id || null
                };
            } else {
                replyData = {
                    id: Date.now(), // 临时ID
                    content: content,
                    username: '当前用户',
                    user_avatar: '',
                    parent_username: '',
                    created_at: new Date().toLocaleString(),
                    likes_count: 0,
                    parent_comment_id: parentCommentId,
                    user_id: null
                };
            }

            console.log('处理后的回复数据:', replyData);
            addNewReply(replyData, parentCommentId);
            updateCommentCount(1);
            showNotification('回复成功！');
        } else {
            if (data.redirect) {
                window.location.href = data.redirect;
            } else {
                showNotification(data.message || '回复失败', 'error');
            }
        }
    })
    .catch(error => {
        console.error('回复错误:', error);
        showNotification('网络错误，请重试', 'error');
    })
    .finally(() => {
        submitBtn.disabled = false;
        submitBtn.textContent = originalText;
    });
}

    // 评论操作处理
    function handleCommentAction(event) {
        const target = event.target;
        const commentLikeBtn = target.closest('.comment-like-btn');
        const commentDeleteBtn = target.closest('.comment-delete-btn');

        if (commentLikeBtn) {
            event.preventDefault();
            handleCommentLike(commentLikeBtn);
        } else if (commentDeleteBtn) {
            event.preventDefault();
            handleCommentDelete(commentDeleteBtn);
        }
    }

    // 评论点赞处理
    function handleCommentLike(button) {
        const commentId = button.dataset.commentId;
        const url = `/meet/social/comment/${commentId}/like/`;

        console.log('评论点赞:', url);

        fetch(url, {
            method: 'POST',
            headers: {
                'X-CSRFToken': csrfToken,
                'X-Requested-With': 'XMLHttpRequest'
            },
        })
        .then(response => {
            console.log('评论点赞响应状态:', response.status);
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }
            return response.json();
        })
        .then(data => {
            console.log('评论点赞响应数据:', data);
            if (data.success) {
                const heartIcon = button.querySelector('i');
                const countSpan = button.querySelector('.comment-like-count');

                if (data.liked) {
                    heartIcon.className = 'fas fa-heart';
                    button.classList.add('liked');
                } else {
                    heartIcon.className = 'far fa-heart';
                    button.classList.remove('liked');
                }

                countSpan.textContent = data.likes_count;
            } else {
                showNotification(data.message || '操作失败', 'error');
            }
        })
        .catch(error => {
            console.error('评论点赞错误:', error);
            showNotification('网络错误，请重试', 'error');
        });
    }

    // 评论删除处理
    function handleCommentDelete(button) {
        if (!confirm('确定要删除这条评论吗？')) {
            return;
        }

        const commentId = button.dataset.commentId;
        const url = `/meet/social/discussion/${discussionId}/delete_comment/`;

        console.log('删除评论:', { url, commentId });

        const formData = new FormData();
        formData.append('comment_id', commentId);
        formData.append('csrfmiddlewaretoken', csrfToken);

        fetch(url, {
            method: 'POST',
            headers: {
                'X-Requested-With': 'XMLHttpRequest'
            },
            body: formData
        })
        .then(response => {
            console.log('删除评论响应状态:', response.status);
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }
            return response.json();
        })
        .then(data => {
            console.log('删除评论响应数据:', data);
            if (data.success) {
                const commentElement = document.querySelector(`[data-comment-id="${commentId}"]`);
                if (commentElement) {
                    // 添加删除动画
                    commentElement.style.transition = 'all 0.3s ease-out';
                    commentElement.style.opacity = '0';
                    commentElement.style.transform = 'translateX(-100%)';

                    setTimeout(() => {
                        commentElement.remove();
                        updateCommentCount(-1);
                        checkEmptyComments();
                        showNotification('评论删除成功');
                    }, 300);
                }
            } else {
                showNotification(data.message || '删除失败', 'error');
            }
        })
        .catch(error => {
            console.error('删除评论错误:', error);
            showNotification('网络错误，请重试', 'error');
        });
    }

    // 添加新评论到列表
    function addNewComment(commentData) {
        const commentsList = document.getElementById('commentsList');
        const noComments = document.getElementById('noComments');

        if (noComments) {
            noComments.remove();
        }

        const commentElement = createCommentElement(commentData);
        if (commentsList.firstChild) {
            commentsList.insertBefore(commentElement, commentsList.firstChild);
        } else {
            commentsList.appendChild(commentElement);
        }

        // 添加动画
        animateElement(commentElement);
    }

    // 添加新回复到列表
    function addNewReply(replyData, parentCommentId) {
        const parentComment = document.querySelector(`[data-comment-id="${parentCommentId}"]`);
        if (!parentComment) {
            console.error('未找到父评论:', parentCommentId);
            return;
        }

        let repliesList = parentComment.querySelector('.replies-list');
        if (!repliesList) {
            repliesList = document.createElement('div');
            repliesList.className = 'replies-list';
            parentComment.appendChild(repliesList);
        }

        const replyElement = createReplyElement(replyData, parentCommentId);
        repliesList.appendChild(replyElement);

        // 添加动画
        animateElement(replyElement);
    }

    // 创建评论元素 - 使用异步头像加载
    function createCommentElement(commentData) {
    console.log('创建评论元素 - 完整数据:', commentData);

    const div = document.createElement('div');
    div.className = 'comment';
    div.dataset.commentId = commentData.id;

    // 安全的内容处理
    const content = commentData.content || '';
    const username = commentData.username || '用户';
    const createdAt = commentData.created_at || new Date().toLocaleString();
    const likesCount = commentData.likes_count || 0;
    const userAvatar = commentData.user_avatar || '';

    div.innerHTML = `
        <div class="comment-header">
            <div class="comment-avatar">
                <!-- 头像区域将由异步加载填充 -->
                <div class="avatar-loading" style="width: 40px; height: 40px; border-radius: 50%; background: #f0f0f0; display: flex; align-items: center; justify-content: center;">
                    <i class="fas fa-spinner fa-spin"></i>
                </div>
            </div>
            <div class="comment-author-info">
                <span class="comment-author">${escapeHtml(username)}</span>
                <span class="comment-date">${escapeHtml(createdAt)}</span>
            </div>
        </div>
        <div class="comment-content">${escapeHtml(content)}</div>
        <div class="comment-actions">
            <button class="comment-like-btn" data-comment-id="${commentData.id}">
                <i class="far fa-heart"></i>
                <span class="comment-like-count">${likesCount}</span>
            </button>
            <button class="comment-reply-btn" data-comment-id="${commentData.id}">
                <i class="fas fa-reply"></i> 回复
            </button>
            <button class="comment-delete-btn" data-comment-id="${commentData.id}">
                <i class="fas fa-trash"></i> 删除
            </button>
        </div>
        <div class="reply-form" id="replyForm-${commentData.id}" style="display: none;">
            <textarea class="reply-input" placeholder="写下你的回复..."></textarea>
            <div class="reply-actions">
                <button class="reply-submit" data-comment-id="${commentData.id}">回复</button>
                <button class="reply-cancel">取消</button>
            </div>
        </div>
        <div class="replies-list"></div>
    `;

    // 异步加载头像
    const avatarContainer = div.querySelector('.comment-avatar');
    loadUserAvatar(
        commentData.user_id,
        username,
        userAvatar,
        avatarContainer
    );

    return div;
}

    // 创建回复元素 - 使用异步头像加载
    function createReplyElement(replyData, parentCommentId) {
    console.log('创建回复元素 - 完整数据:', replyData);

    const div = document.createElement('div');
    div.className = 'comment reply';
    div.dataset.commentId = replyData.id;

    // 安全的内容处理
    const content = replyData.content || '';
    const username = replyData.username || '用户';
    const parentUsername = replyData.parent_username || '用户';
    const createdAt = replyData.created_at || new Date().toLocaleString();
    const likesCount = replyData.likes_count || 0;
    const userAvatar = replyData.user_avatar || '';

    div.innerHTML = `
        <div class="comment-header">
            <div class="comment-avatar">
                <!-- 头像区域将由异步加载填充 -->
                <div class="avatar-loading" style="width: 32px; height: 32px; border-radius: 50%; background: #f0f0f0; display: flex; align-items: center; justify-content: center;">
                    <i class="fas fa-spinner fa-spin" style="font-size: 0.8rem;"></i>
                </div>
            </div>
            <div class="comment-author-info">
                <span class="comment-author">${escapeHtml(username)}</span>
                <span class="comment-date">${escapeHtml(createdAt)}</span>
            </div>
        </div>
        <div class="comment-content">
            <span class="reply-to">@${escapeHtml(parentUsername)}</span>
            ${escapeHtml(content)}
        </div>
        <div class="comment-actions">
            <button class="comment-like-btn" data-comment-id="${replyData.id}">
                <i class="far fa-heart"></i>
                <span class="comment-like-count">${likesCount}</span>
            </button>
            <button class="comment-reply-btn" data-comment-id="${parentCommentId}">
                <i class="fas fa-reply"></i> 回复
            </button>
            <button class="comment-delete-btn" data-comment-id="${replyData.id}">
                <i class="fas fa-trash"></i> 删除
            </button>
        </div>
    `;

    // 异步加载头像
    const avatarContainer = div.querySelector('.comment-avatar');
    loadUserAvatar(
        replyData.user_id,
        username,
        userAvatar,
        avatarContainer
    );

    return div;
}

    // 更新评论计数
    function updateCommentCount(change = 0) {
        const commentsCount = document.getElementById('commentsCount');
        if (commentsCount) {
            const currentText = commentsCount.textContent;
            const currentCount = parseInt(currentText) || 0;
            const newCount = Math.max(0, currentCount + change);
            commentsCount.textContent = `${newCount} 条评论`;
        }

        // 同时更新帖子操作区的评论计数
        const discussionCommentCount = document.querySelector('.comment-scroll-btn .count');
        if (discussionCommentCount) {
            const currentCount = parseInt(discussionCommentCount.textContent) || 0;
            discussionCommentCount.textContent = Math.max(0, currentCount + change);
        }
    }

    // 检查是否没有评论
    function checkEmptyComments() {
        const commentsList = document.getElementById('commentsList');
        if (commentsList && commentsList.children.length === 0) {
            commentsList.innerHTML = `
                <div class="no-comments" id="noComments">
                    <i class="far fa-comment-dots" style="font-size: 2rem; margin-bottom: 1rem; color: #ddd;"></i>
                    <p>还没有评论，快来发表第一条评论吧！</p>
                </div>
            `;
        }
    }

    // 动画效果
    function animateElement(element) {
        element.style.opacity = '0';
        element.style.transform = 'translateY(-20px)';

        setTimeout(() => {
            element.style.transition = 'all 0.3s ease-out';
            element.style.opacity = '1';
            element.style.transform = 'translateY(0)';
        }, 10);
    }

    // 显示通知
    function showNotification(message, type = 'success') {
        // 移除现有通知
        const existingNotification = document.querySelector('.notification');
        if (existingNotification) {
            existingNotification.remove();
        }

        const notification = document.createElement('div');
        notification.className = `notification ${type}`;
        notification.innerHTML = `
            <span>${message}</span>
            <button class="notification-close">&times;</button>
        `;

        document.body.appendChild(notification);

        // 关闭按钮事件
        const closeBtn = notification.querySelector('.notification-close');
        closeBtn.addEventListener('click', () => {
            notification.remove();
        });

        // 3秒后自动消失
        setTimeout(() => {
            if (notification.parentNode) {
                notification.remove();
            }
        }, 3000);
    }

    // HTML转义
    function escapeHtml(text) {
        if (!text) return '';
        const div = document.createElement('div');
        div.textContent = text;
        return div.innerHTML;
    }
});

// 头像加载错误处理
function handleAvatarError(img) {
    const parent = img.parentElement;
    if (parent && parent.classList.contains('comment-avatar')) {
        const username = img.alt || 'User';
        const firstLetter = username.charAt(0).toUpperCase();
        parent.innerHTML = `<div class="avatar-img" style="background: linear-gradient(135deg, #FF6B35, #E55A2B); color: white; display: flex; align-items: center; justify-content: center; font-weight: bold;">${firstLetter}</div>`;

        // 可以在这里添加重试逻辑
        setTimeout(() => {
            // 3秒后重试加载头像
            const newSrc = img.src + (img.src.includes('?') ? '&' : '?') + 'retry=' + Date.now();
            const newImg = new Image();
            newImg.onload = function() {
                parent.innerHTML = `<img src="${newSrc}" alt="${username}" class="avatar-img">`;
            };
            newImg.src = newSrc;
        }, 3000);
    }
}

// 调试函数
function debugReplyData(replyData, functionName) {
    console.log(`${functionName} - 回复数据:`, {
        id: replyData.id,
        username: replyData.username,
        content: replyData.content,
        parent_comment_id: replyData.parent_comment_id,
        user_avatar: replyData.user_avatar,
        likes_count: replyData.likes_count,
        created_at: replyData.created_at,
        fullData: replyData
    });
}

// 关注/取消关注功能 - 完整版本
function toggleFollow(button) {
    const userId = button.getAttribute('data-user-id');
    const isCurrentlyFollowing = button.querySelector('.follow-text').textContent.includes('已关注');

    if (!userId) {
        showToast('用户ID无效', 'error');
        return;
    }

    button.disabled = true;
    const originalHtml = button.innerHTML;

    // 显示加载状态
    button.innerHTML = '<i class="fas fa-spinner fa-spin me-1"></i> 处理中...';

    fetch('/user/toggle_follow/', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'X-CSRFToken': getCsrfToken(),
            'X-Requested-With': 'XMLHttpRequest'
        },
        body: JSON.stringify({
            user_id: parseInt(userId)
        })
    })
    .then(response => {
        if (!response.ok) {
            throw new Error('网络响应不正常');
        }
        return response.json();
    })
    .then(data => {
        console.log('关注响应:', data);
        if (data.success) {
            // 更新按钮状态
            if (data.action === 'followed') {
                button.innerHTML = '<i class="fas fa-check me-1"></i> 已关注';
                button.classList.remove('btn-outline-primary');
                button.classList.add('btn-primary');
                showToast(`已关注 ${data.target_username}`, 'success');
            } else {
                button.innerHTML = '<i class="fas fa-plus me-1"></i> 关注';
                button.classList.remove('btn-primary');
                button.classList.add('btn-outline-primary');
                showToast(`已取消关注 ${data.target_username}`, 'info');
            }

            // 发送实时更新通知到个人中心页面
            notifyPersonCenter('follow_updated', {
                userId: parseInt(userId),
                action: data.action,
                targetUsername: data.target_username,
                stats: data.stats
            });

        } else {
            showToast(data.message || '操作失败', 'error');
            // 恢复原始状态
            button.innerHTML = originalHtml;
        }
    })
    .catch(error => {
        console.error('关注操作失败:', error);
        showToast('网络错误，请重试', 'error');
        // 恢复原始状态
        button.innerHTML = originalHtml;
    })
    .finally(() => {
        button.disabled = false;
    });
}

// 获取 CSRF Token
function getCsrfToken() {
    const csrfTokenElement = document.querySelector('[name=csrfmiddlewaretoken]');
    if (csrfTokenElement) {
        return csrfTokenElement.value;
    }

    // 从 cookie 中获取
    const name = 'csrftoken';
    let cookieValue = null;
    if (document.cookie && document.cookie !== '') {
        const cookies = document.cookie.split(';');
        for (let i = 0; i < cookies.length; i++) {
            const cookie = cookies[i].trim();
            if (cookie.substring(0, name.length + 1) === (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}

// 向个人中心页面发送通知
function notifyPersonCenter(type, data) {
    const eventData = {
        type: type,
        data: data,
        timestamp: Date.now(),
        source: 'discussion_detail' // 或 'active_detail'
    };

    // 使用 localStorage 作为跨页面通信机制
    localStorage.setItem('person_center_update', JSON.stringify(eventData));

    // 触发 storage 事件（用于同域名下的其他页面监听）
    window.dispatchEvent(new StorageEvent('storage', {
        key: 'person_center_update',
        newValue: JSON.stringify(eventData)
    }));

    console.log('已发送关注更新通知到个人中心:', eventData);
}

// 显示通知函数
function showToast(message, type = 'success') {
    // 创建自定义通知
    const notification = document.createElement('div');
    notification.className = `alert alert-${type === 'error' ? 'danger' : type} alert-dismissible fade show`;
    notification.style.cssText = `
        position: fixed;
        top: 20px;
        right: 20px;
        z-index: 9999;
        min-width: 300px;
    `;
    notification.innerHTML = `
        <strong>${type === 'success' ? '成功' : type === 'error' ? '错误' : '信息'}</strong> ${message}
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    `;

    document.body.appendChild(notification);

    // 3秒后自动消失
    setTimeout(() => {
        if (notification.parentNode) {
            notification.parentNode.removeChild(notification);
        }
    }, 3000);
}
</script>
{% endblock %}